package com.ldc.security.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ldc.model.SysRole;
import com.ldc.model.SysUser;
import com.ldc.model.SysUserRole;
import com.ldc.security.model.SecurityGrantedAuthority;
import com.ldc.security.model.SecurityUser;
import com.ldc.service.service.RoleService;
import com.ldc.service.service.UserRoleService;
import com.ldc.service.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 功能说明
 *
 * @auther liudc
 * @since 2023/6/11
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser userBean = findByUserName(username);
        if (userBean == null) {
            throw new UsernameNotFoundException("Find account does not exist");
        }
        List<SysUserRole> userRoleBeans = findByUserId(userBean.getId());
        List<SecurityGrantedAuthority> authorityList = new ArrayList<>();
        for (SysUserRole item : userRoleBeans) {
            SysRole roleBean = findByRoleId(item.getRoleId());
            authorityList.add(new SecurityGrantedAuthority(roleBean.getRole()));
        }
        SecurityUser user = new SecurityUser(userBean, authorityList);
        return user;
    }


    private SysUser findByUserName(String userName) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName, userName);
        return userService.getOne(queryWrapper);
    }

    private List<SysUserRole> findByUserId(long userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        return userRoleService.list(queryWrapper);
    }

    private SysRole findByRoleId(long roleId) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getId, roleId);
        return roleService.getOne(queryWrapper);
    }
}
